<template>
  <el-row :gutter="20">
    <el-col :span="6">
      <el-card>
        <el-form
          :rules="rules"
          :inline="true"
          ref="conncectFormRef"
          :model="connectForm"
          class="form-contain"
          size="small"
        >
          <el-form-item
            :label="t('robokit.port')"
            prop="port"
          >
            <el-input
              type="number"
              v-model.number="connectForm.port"
              :disabled="robokitServerStatus"
              placeholder="连接端口"
              @keuyp.enter="connect(conncectFormRef)"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              :type="robokitServerStatus ? 'danger' : 'primary'"
              @click="connect(conncectFormRef)"
              :loading="loading"
            >
              {{ t(robokitServerStatus ? 'robokit.disconnect' : 'robokit.creat' ) }}
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 根据消息类型展示不同的表单 -->
        <el-form
          ref="ruleFormRef"
          :model="robokitForm"
          :rules="rules"
          class="demo-ruleForm"
          label-position="top"
          size="small"
        >
          <el-form-item
            type="number"
            :label="t('robokit.messageType')"
            prop="messageType"
          >
            <el-input
              type="number"
              v-model.number="robokitForm.messageType"
              :placeholder="t('robokit.messageType')"
            />
          </el-form-item>

          <el-form-item
            type="number"
            :label="t('robokit.messageSerial')"
            prop="messageSerial"
          >
            <el-input
              v-model.number="robokitForm.messageSerial"
              :placeholder="t('robokit.messageSerial')"
            />
          </el-form-item>

          <el-form-item
            :label="t('robokit.message')"
            prop="message"
          >
            <el-input
              type="textarea"
              :rows="18"
              v-model="robokitForm.message"
              :placeholder="t('robokit.message')"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm(ruleFormRef)"
              :disabled="!robokitServerStatus"
              :loading="loading"
            >
              {{ t('robokit.send') }}
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">
              {{ t('robokit.reset') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
    <el-col :span="18">
      <Log />
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { ElMessage, FormInstance, FormRules, TabsPaneContext } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import Log from '@/components/Log/robokitLog.vue'
import { closeServer, creatServer, sendMessageByServer } from '@/api/robokit'
import { useI18n } from 'vue-i18n'
import { robokitStore } from '@/store/robokitStore'
import { storeToRefs } from 'pinia'
import { RobokitMessage } from '@/types/robokit'

const { t } = useI18n()

const store = robokitStore()
const ruleFormRef = ref<FormInstance>()
const loading = ref(false)

// // 初始化websocket
// initWebSocket('simulator')
const { robokitServerStatus, robokitServerPort } = storeToRefs(store) // 连接状态

// 连接信息表单
const connectForm = reactive({
  port: robokitServerPort.value
})

const robokitForm:RobokitMessage = reactive({
  messageType: 0,
  messageSerial: 0,
  message: ''
})

// 表单校验规则
const rules = reactive<FormRules>({
  ip: [
    { required: true, message: '请填写IP地址', trigger: 'blur' }
  ],
  port: [
    {
      required: true,
      message: '请填写连接端口',
      trigger: 'change'
    },
    { type: 'number', message: '端口号必须为数字类型' }
  ],
  messageType: [
    { required: true, message: '请填写报文类型', trigger: 'blur' },
    { type: 'number', message: '报文类型必须为数字类型' }
  ],
  messageSerial: [
    { required: true, message: '请填写报文序号', trigger: 'blur' },
    { type: 'number', message: '报文序号必须为数字类型' }
  ]
  // message: [
  //   {
  //     required: true,
  //     message: '请填写报文',
  //     trigger: 'change'
  //   }
  // ]
})

// 连接
const conncectFormRef = ref<FormInstance>()
const connect = async (formEl: FormInstance | undefined) => {
  // 储存ip和port，解决刷新丢失
  store.setRobokitServerPort(connectForm.port)

  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      if (robokitServerStatus.value) {
        // 断开连接
        closeServer().then(res => {
          store.setRobokitServerStatus(false)
        }).finally(() => {
          loading.value = false
        })
      } else {
        // 建立连接
        creatServer(connectForm.port).then(res => {
          store.setRobokitServerStatus(true)
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 发送消息
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      sendMessageByServer(robokitForm).then(res => {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'success',
          duration: 1000
        })
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

// 重置消息表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>
<style scoped lang="scss">
.form-contain {
  margin-bottom: 20px;
}
</style>
